package com.sgmw.sales.tool.kong.sign.headers;

import java.util.Map;
import java.util.Map.Entry;

public class SignHeaderRequestLine implements RequestHeader{
	private HttpVersion httpVersion;
	private String httpMethod;
	private String uri;
	private String uriAndQueryParameterString;
	private String value;
	
	public SignHeaderRequestLine(String httpMethod, String uri, Map<String, String> queryParameters) {
		 this(HttpVersion.V1_1, httpMethod, uri, queryParameters);
	}
	
	public SignHeaderRequestLine(HttpVersion httpVersion, String httpMethod, String uri, Map<String, String> queryParameters) {
		this.httpVersion = httpVersion;
		this.httpMethod = httpMethod;
		this.uri = uri;
		
		int i = 0;
		StringBuilder sb = new StringBuilder();
		if (queryParameters != null) {
			//排序处理
//			List<String> keys=new ArrayList<String>(queryParameters.keySet());
//			Collections.sort(keys);
//			
//			String value = "";
//			for (String key : keys) {
//				value = queryParameters.get(key);
//				if (i == 0) {
//					sb.append(key).append("=").append(value);
//				} else {
//					sb.append("&").append(key).append("=").append(value);
//				}
//				i++;
//			}
			
			for (Entry<String, String> entry : queryParameters.entrySet()) {
				if (i == 0) {
					sb.append(entry.getKey()).append("=").append(entry.getValue());
				} else {
					sb.append("&").append(entry.getKey()).append("=").append(entry.getValue());
				}
				i++;
			}
		}
		if (sb.length() > 0) {
			this.uriAndQueryParameterString = this.uri + "?" + sb.toString();
		} else {
			this.uriAndQueryParameterString = this.uri;
		}
		value= this.httpMethod.toUpperCase() + " " + uriAndQueryParameterString + " " + "HTTP/" + this.httpVersion;
	}

//	/**
//	 * 注意这里签名的时候预期的http协议是1.1，但最终到达kong的请求有可能不是1.1的，原因：
//	 * 请求经过nginx proxy_pass后默认是使用http 1.0，这个时候可以增加转发请求的版本设置 proxy_http_version 1.1;
//	 * 或者修改签名字符串版本协议为:1.0
//	 */
//	@Override
//	public String getSignString() {
//		String httpMethod = this.httpMethod.toUpperCase();
////		String signString = httpMethod+" "+ uriAndQueryParameterString + " " +"HTTP/1.0";
//		String signString = httpMethod+" "+ uriAndQueryParameterString + " " +"HTTP/1.1";
//		return signString;
//	}
	
	@Override
	public String getName() {
		return "request-line";
	}

	/**
	 * 注意这里签名的时候预期的http协议是1.1，但最终到达kong的请求有可能不是1.1的，原因：
	 * 请求经过nginx proxy_pass后默认是使用http 1.0，这个时候可以增加转发请求的版本设置 proxy_http_version 1.1;
	 * 或者修改签名字符串版本协议为:1.0
	 */
	@Override
	public String getValue() {
		return value;
	}

	@Override
	public String toString() {
		return getName()+": "+value;
	}
}
